home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: newsfeed.acns.nwu.edu!ftpbox!mothost!schbbs!news
- From: Wendy Weiss x5693 <weiss>
- Subject: C access to C++ object data
- Content-Type: text/plain
- Organization: Motorola GSTG, Scottsdale, AZ
- Date: Fri, 12 Jan 1996 20:58:45 GMT
- Message-ID: <1996Jan12.205845.22708@schbbs.mot.com>
- X-Mailer: Mozilla 1.1 (X11; U; SunOS 4.1C sun4)
- Mime-Version: 1.0
- X-Url: file:/tmp_mnt/home/pooh/weiss/cplusplus
- Content-Transfer-Encoding: 7bit
- Sender: news@schbbs.mot.com (SCHBBS News Account)
- Nntp-Posting-Host: 192.9.2.17
-
- I'm trying to interface between C and C++. I am able to
- call C++ member functions from C (using the extern "C" and nonmember
- functions). Now I want to access object data from C. I have looked
- at the FAQ:
-
- >Can my C function access data in an object of a C++ class?
- >
- >Sometimes.
- >
- >You can safely access a C++ object's data from a C function if the C++ class:
- >
- > * has no virtual functions (including inherited virtual fns)
- > * has all its data in the same access-level section
- > (private/protected/public)
- > * has no fully-contained subobjects with virtual fns
- >
- >
-
- and I have no problem with all the restrictions.
-
-
- Using the example from the C++ faq - I want to access a_ from c-fn.c.
- How do I refer to a_ in c-fn.c??? I know that a_ needs to be
- public (I changed that from the original example) .
- fred->a_ doesn't work, since C doesn't know the structure of the
- object. I know I could write get/put functions, but I want to access
- it directly. Any help would be appreciated.
-
-
-
- Here's an example:
-
- /****** C/C++ header file: Fred.h ******/
- #ifdef __cplusplus /*"__cplusplus" is #defined if/only-if compiler is C++*/
- extern "C" {
- #endif
-
- #ifdef __STDC__
- extern void c_fn(struct Fred*); /* ANSI-C prototypes */
- extern struct Fred* cplusplus_callback_fn(struct Fred*);
- #else
- extern void c_fn(); /* K&R style */
- extern struct Fred* cplusplus_callback_fn();
- #endif
-
- #ifdef __cplusplus
- }
- #endif
-
- #ifdef __cplusplus
- class Fred {
- public:
- Fred();
- void wilma(int);
- /* private:*/
- int a_;
- };
- #endif
-
- "Fred.C" would be a C++ module:
-
- #include "Fred.h"
- Fred::Fred() : a_(0) { }
- void Fred::wilma(int a) : a_(a) { }
-
- Fred* cplusplus_callback_fn(Fred* fred)
- {
- fred->wilma(123);
- return fred;
- }
-
- "main.C" would be a C++ module:
-
- #include "Fred.h"
- int main()
- {
- Fred fred;
- c_fn(&fred);
- return 0;
- }
-
- "c-fn.c" would be a C module:
-
- #include "Fred.h"
- void c_fn(struct Fred* fred)
- {
- cplusplus_callback_fn(fred);
- }
-
-
-
- Thanks,
- Wendy Weiss
- weiss@pooh.geg.mot.com
- weiss@primenet.com
-